package http

import (
	"context"
	"github.com/go-kit/kit/auth/jwt"
	"gysa-share01/common"
	"gysa-share01/exception"
	"gysa-share01/models/db"
	"gysa-share01/models/order"
	"gysa-share01/user-service/auth"
	"gysa-share01/user-service/grpc/client"
	service_user "gysa-share01/user-service/user/proto"
)

type PayType int

const (
	BalancePayment PayType = 0
)

var goods = struct {
	ID    int
	Price uint64
}{100, 10000}

type OrderServiceHttpInterface interface {
	Create(userId, goodsId int, goodsTotal int) (order.Order, error)
	Pay(ctx context.Context, orderId int, payType PayType) (order.Order, error)
}

type OrderServiceHttp struct {
}

func (o OrderServiceHttp) Create(userId, goodsId int, goodsTotal int) (ord order.Order, err error) {
	if goodsId != goods.ID {
		err = exception.NewGeneralException("商品不存在", exception.RESOURCE_DOES_NOT_EXIST)
		return
	}

	model, err := db.Instance()
	if err != nil {
		return
	}

	ord = order.Order{
		UserId:    int64(userId),
		Price:     goods.Price * uint64(goodsTotal),
		PayStatus: int8(order.PAY_STATUS_NOT_PAY),
	}

	err = model.Create(&ord).Error
	if err != nil {
		return
	}

	return
}

func (o OrderServiceHttp) Pay(ctx context.Context, orderId int, payType PayType) (ord order.Order, err error) {
	user, ok := ctx.Value(jwt.JWTClaimsContextKey).(*auth.AuthClaims)
	if !ok {
		err = exception.NewGeneralException("jwt 异常", exception.SYSTEM_ERROR)
		return
	}
	model, err := db.Instance()
	if err != nil {
		return
	}

	err = model.First(&ord, orderId).Error
	if err != nil {
		return
	}

	if (ord == order.Order{}) {
		err = exception.NewGeneralException("订单不存在", exception.RESOURCE_DOES_NOT_EXIST)
		return
	}
	common.Logger.Println(user.Uid, int32(user.Uid))
	//调用远程rpc服务获取用户余额并且判断余额
	userInfo, err := client.Info(&service_user.InfoRequest{UserId: int32(user.Uid)}, ctx)
	if err != nil {
		return
	}
	if userInfo.ErrCode > 0 {
		err = exception.NewGeneralException(userInfo.ErrMsg, exception.ExceptionCode(userInfo.ErrCode))
		return
	}

	if userInfo.User.Money < ord.Price {
		err = exception.NewGeneralException("余额不足", exception.ACCESS_DENIED)
		return
	}

	//开启事务
	//tcc事务逻辑流程

	return
}
